package state.util;

public class NumberUtil {
  public static final int ERROR_VALUE = -99999;
  
  public static int parseInt(String s) {
    int radix = 10;
    int result = 0;
    boolean negative = false;
    int i = 0, max = s.length();
    int limit;
    int multmin;
    int digit;

    if (max > 0) {
      if (s.charAt(0) == '-') {
        negative = true;
        limit = Integer.MIN_VALUE;
        i++;
      } else {
        limit = -Integer.MAX_VALUE;
      }
      multmin = limit / radix;
      if (i < max) {
        digit = Character.digit(s.charAt(i++), radix);
        if (digit < 0) {
          return ERROR_VALUE;
        } else {
          result = -digit;
        }
      }
      while (i < max) {
        // Accumulating negatively avoids surprises near MAX_VALUE
        digit = Character.digit(s.charAt(i++), radix);
        if (digit < 0) {
          return ERROR_VALUE;
        }
        if (result < multmin) {
          return ERROR_VALUE;
        }
        result *= radix;
        if (result < limit + digit) {
          return ERROR_VALUE;
        }
        result -= digit;
      }
    } else {
      return ERROR_VALUE;
    }
    if (negative) {
      if (i > 1) {
        return result;
      } else { /* Only got "-" */
        return ERROR_VALUE;
      }
    } else {
      return -result;
    }
  }
}
